<template>
  <div class="main">

    <PlusSearch
      v-model="state"
      :columns="columns"
      :show-number="2"
      @change="handleChange"
      @search="handleSearch"
      @reset="handleReset"
    />




    <el-form
      ref="formRef"
      :inline="true"
      :model="form"
      class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px] overflow-auto"
    >
      <el-form-item label="商户名：" prop="merchantName">
        <el-input
          v-model="form.merchantName"
          placeholder="请输入商户名"
          clearable
          class="!w-[180px]"
        />
      </el-form-item>
      <el-form-item label="经营地址" prop="address">
        <el-input
          v-model="form.address"
          placeholder="请输入经营地址"
          clearable
          class="!w-[180px]"
        />
      </el-form-item>
      <el-form-item label="经营类型：" prop="businessType">
        <el-select
          v-model="form.businessType"
          placeholder="请选择状态"
          clearable
          class="!w-[180px]"
        >
          <el-option label="已启用" value="1" />
          <el-option label="已停用" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon('ri:search-line')"
          :loading="loading"
          @click="onSearch"
        >
          搜索
        </el-button>
        <el-button :icon="useRenderIcon(Refresh)" @click="resetForm(formRef)">
          重置
        </el-button>
      </el-form-item>
    </el-form>
    <div
      ref="contentRef"
      :class="['flex', deviceDetection() ? 'flex-wrap' : '']"
    >
      <PureTableBar
        class="w-full"
        title="商户管理"
        :columns="columns"
        @refresh="onSearch"
      >
        <template #buttons>
          <el-button
            type="primary"
            :icon="useRenderIcon(AddFill)"
            @click="openDialog()"
          >
            新增商户
          </el-button>
        </template>
        <template v-slot="{ size, dynamicColumns }">
          <pure-table
            ref="tableRef"
            align-whole="center"
            showOverflowTooltip
            table-layout="auto"
            :loading="tableLoading"
            :size="size"
            adaptive
            :adaptiveConfig="{ offsetBottom: 108 }"
            :data="dataList"
            :columns="dynamicColumns"
            :pagination="{ ...pagination, size }"
            :header-cell-style="{
              background: 'var(--el-fill-color-light)',
              color: 'var(--el-text-color-primary)'
            }"
            @page-size-change="handleSizeChange"
            @page-current-change="handleCurrentChange"
          >
            <template #operation="{ row }">
              <el-button
                class="reset-margin"
                link
                type="primary"
                :size="size"
                :icon="useRenderIcon(EditPen)"
                @click="openDialog('修改', row)"
              >
                修改
              </el-button>
              <el-popconfirm title="确认删除吗？" @confirm="handleDelete(row)">
                <template #reference>
                  <el-button
                    class="reset-margin"
                    link
                    type="primary"
                    :size="size"
                    :icon="useRenderIcon(Delete)"
                  >
                    删除
                  </el-button>
                </template>
              </el-popconfirm>
            </template>
          </pure-table>
        </template>
      </PureTableBar>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, computed, nextTick, onMounted, h } from "vue";
import { message } from "@/utils/message";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import type { PaginationProps } from "@pureadmin/table";

import type { PlusColumn } from 'plus-pro-components'




import { addDialog } from "@/components/ReDialog";
import editForm from "./form.vue";
import {
  delay,
  subBefore,
  deviceDetection,
  useResizeObserver
} from "@pureadmin/utils";

import { merchantsList, addMerchants } from "@/api/zhaoyuan";
// import Database from "@iconify-icons/ri/database-2-line";
// import More from "@iconify-icons/ep/more-filled";
import Delete from "@iconify-icons/ep/delete";
import EditPen from "@iconify-icons/ep/edit-pen";
import Refresh from "@iconify-icons/ep/refresh";
import Menu from "@iconify-icons/ep/menu";
import AddFill from "@iconify-icons/ri/add-circle-line";
import Close from "@iconify-icons/ep/close";
import Check from "@iconify-icons/ep/check";

defineOptions({
  name: "SystemRole"
});
const loading = ref(false);
const form = reactive({
  merchantName: "",
  businessType: "",
  address: ""
});

//重置表单
const resetForm = formEl => {
  if (!formEl) return;
  formEl.resetFields();
  onSearch();
};
//执行搜索
async function onSearch() {
  loading.value = true;
  getTableData();
  loading.value = false;
}
const formRef = ref();
const dataList = ref([]);
const tableLoading = ref(false);
const page = ref(1);
const size = ref(10);
const pagination = reactive<PaginationProps>({
  total: 0,
  pageSize: 10,
  currentPage: 1,
  background: true
});
const getTableData = async () => {
  if (tableLoading.value) {
    return;
  }
  tableLoading.value = true;
  console.log(page);
  const res = await merchantsList({
    ...form,
    ...{ page: page.value, size: size.value }
  });
  dataList.value = res._embedded.items;
  pagination.total = res.page.totalElements;
  pagination.pageSize = res.page.size;
  pagination.currentPage = res.page.numnber;
  page.value = page.value + 1;
  tableLoading.value = false;
};

//表格列
const columns: TableColumnList = [
  {
    label: "ID",
    prop: "id"
  },
  {
    label: "商户名称",
    prop: "merchantName"
  },
  {
    label: "经营类型",
    prop: "businessType"
  },
  {
    label: "经营地址",
    prop: "address"
  },

  {
    label: "联系电话",
    prop: "contactInfo",
    minWidth: 160
  },
  {
    label: "经营年限",
    prop: "operationYears",
    minWidth: 160
  },
  {
    label: "员工人数",
    prop: "operationYears",
    minWidth: 160
  },
  {
    label: "操作",
    fixed: "right",
    width: 210,
    slot: "operation"
  }
];
const iconClass = computed(() => {
  return [
    "w-[22px]",
    "h-[22px]",
    "flex",
    "justify-center",
    "items-center",
    "outline-none",
    "rounded-[4px]",
    "cursor-pointer",
    "transition-colors",
    "hover:bg-[#0000000f]",
    "dark:hover:bg-[#ffffff1f]",
    "dark:hover:text-[#ffffffd9]"
  ];
});

function handleDelete(row) {
  message(`您删除了角色名称为${row.name}的这条数据`, { type: "success" });
  onSearch();
}

function handleSizeChange(val: number) {
  page.value = 1;
  size.value = val;
  getTableData();
  console.log(`${val} items per page`);
}

function handleCurrentChange(val: number) {
  page.value = val;
  getTableData();
  console.log(`current page: ${val}`);
}

function openDialog(title = "新增", row?) {
  addDialog({
    title: `${title}商户`,
    props: {
      formInline: {
        merchantName: row?.name ?? "",
        businessType: row?.businessType ?? "",
        address: row?.address ?? "",
        latitude: row?.latitude ?? "",
        longitude: row?.longitude ?? "",
        contactInfo: row?.contactInfo ?? "",
        operationYears: row?.operationYears ?? "",
        businessScale: row?.businessScale ?? "",
        storefrontImageUrl: row?.storefrontImageUrl ?? "",
        productImages: row?.productImages ?? [],
        interiorImages: row?.interiorImages ?? []
      }
    },
    width: "60%",
    draggable: true,
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
    beforeSure: (done, { options }) => {
      const FormRef = formRef.value.getRef();
      const curData = options.props.formInline;
      function chores() {
        message(`您${title}了角色名称为${curData.name}的这条数据`, {
          type: "success"
        });
        done(); // 关闭弹框
        onSearch(); // 刷新表格数据
      }
      FormRef.validate(valid => {
        if (valid) {
          console.log("curData", curData);
          // 表单规则校验通过
          if (title === "新增") {
            // 实际开发先调用新增接口，再进行下面操作
            addMerchants(curData).then(res => {
              chores();
            });
          } else {
            // 实际开发先调用修改接口，再进行下面操作
            chores();
          }
        }
      });
    }
  });
}

onMounted(() => {
  getTableData();
});
</script>

<style lang="scss" scoped>
:deep(.el-dropdown-menu__item i) {
  margin: 0;
}

.main-content {
  margin: 24px 24px 0 !important;
}

.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
  }
}
</style>
